package com.opmsys.interceptor;

import com.opmsys.result.VisiteDeny;
import com.opmsys.utils.jsonWebToken.JsonWebTokenUtil;
import com.opmsys.utils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);

    private static final ThreadLocal<Long> START_THREAD_LOCAL = new ThreadLocal<>();

    final private RedisUtil redisUtil;
    final private JsonWebTokenUtil jsonWebTokenUtil;

    public LoginInterceptor(RedisUtil redisUtil, JsonWebTokenUtil jsonWebTokenUtil) {
        this.redisUtil = redisUtil;
        this.jsonWebTokenUtil = jsonWebTokenUtil;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String JWT = request.getHeader("JWT");
        if (jsonWebTokenUtil.verifyJWT(JWT)){
            long number = jsonWebTokenUtil.getNumberFromJWT(JWT);//验证jwt合法性
            return redisUtil.exists(Long.toString(number));//验证jwt是否被存储在redis中
        }

        new VisiteDeny(response,"你尚未登录，请先登录！");

        return false;
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }



}
